export default defineUnlistedScript({
  main() {
    // 保存原始的fetch函数
    const originalFetch = window.fetch;
    
    // 创建一个自定义事件来传递数据
    function emitFetchEvent(type, data) {
      const event = new CustomEvent('fetch-event', {
        detail: { type, data }
      });
      document.dispatchEvent(event);
    }

    // 重写fetch函数
    window.fetch = async function(...args) {
      const [resource, config] = args;
      const requestUrl = typeof resource === 'string' ? resource : resource.url;
      
      // 发送请求信息
      emitFetchEvent('request', {
        url: requestUrl,
        method: config?.method || 'GET',
        body: config?.body,
        headers: config?.headers
      });

      try {
        const response = await originalFetch.apply(this, args);
        const clone = response.clone();
        
        // 读取响应数据
        const text = await clone.text();
        let responseData = text;
        try {
          responseData = JSON.parse(text);
        } catch (e) {}

        // 发送响应信息
        emitFetchEvent('response', {
          url: requestUrl,
          method: config?.method || 'GET',
          status: response.status,
          response: responseData
        });

        return response;
      } catch (error) {
        emitFetchEvent('error', {
          url: requestUrl,
          error: error.message
        });
        throw error;
      }
    };
  },
});